package com.cugmarket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cugmarket.dto.Result;
import com.cugmarket.entity.ProductType;
import com.cugmarket.entity.UserFollows;
import com.cugmarket.mapper.UserFollowsMapper;
import com.cugmarket.service.UserFollowsService;
import com.cugmarket.service.UserService;
import com.cugmarket.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.cugmarket.constant.MessageConstant.FOLLOW_FAIL;
import static com.cugmarket.constant.MessageConstant.UN_FOLLOW_FAIL;

@Service
public class UserFollowsServiceImpl extends ServiceImpl<UserFollowsMapper, UserFollows> implements UserFollowsService {
    @Resource
    private UserService userService;
    @Resource
    private UserFollowsMapper userFollowsMapper;

    @Override
    public Boolean follow(String followUserId, Boolean isFollow) {
        // 1获取当前登录用户
        String userId = UserHolder.getUser();
        // 2判断是关注还是取关
        if (isFollow) {
            // 3关注，新增
            UserFollows userFollows = new UserFollows();
            userFollows.setUserId(userId);
            userFollows.setFollowedUserId(followUserId);
            boolean isSuccess = save(userFollows);
            if (!isSuccess) {
                throw new RuntimeException(FOLLOW_FAIL);
            }
        }
        else{
            LambdaQueryWrapper<UserFollows> queryWrapper = new LambdaQueryWrapper<UserFollows>()
                    .eq(UserFollows::getUserId, userId).eq(UserFollows::getFollowedUserId, followUserId);
            int success = userFollowsMapper.delete(queryWrapper);
            if (success == 0) {
                throw new RuntimeException(UN_FOLLOW_FAIL);
            }
        }
        return true;
    }

    @Override
    public boolean isFollow(String followUserId) {
        String userId = UserHolder.getUser();
        LambdaQueryWrapper<UserFollows> queryWrapper = new LambdaQueryWrapper<UserFollows>()
                .eq(UserFollows::getUserId, userId)
                .eq(UserFollows::getFollowedUserId, followUserId);
        Long count = userFollowsMapper.selectCount(queryWrapper);
        return count > 0;
    }

}
